package com.geektime.congestion.auth.domain;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.geektime.congestion.auth.constants.Constants;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@NoArgsConstructor
@Getter
@ToString
public class AuthToken {

    private static final long expiresIn = TimeUnit.MINUTES.toMillis(1);

    private String token;

    private long createdAt;

    private long expiresAt;

    public AuthToken(String token, long createdAt) {
        this.token = token;
        this.createdAt = createdAt;
    }

    public AuthToken(String token, long createdAt, long expiresAt) {
        this.token = token;
        this.createdAt = createdAt;
        this.expiresAt = expiresAt;
    }


    public static AuthToken create(String baseurl, long createdAt, Map<String, String> params) {
        StringBuilder plain = new StringBuilder(baseurl).append('?');
        params.put("timestamp", String.valueOf(createdAt));
        params.forEach((k, v) -> plain.append(k).append('=').append(v).append('&'));
        plain.setLength(plain.length() - 1);
        String plainText = plain.toString();
        AES aes = new AES(Mode.CTS, Padding.PKCS5Padding, Constants.KEY, Constants.IV);
        String cipherHex = aes.encryptHex(plainText);
        return new AuthToken(cipherHex, createdAt);
    }

    public boolean isExpired() {
        if (expiresAt == 0) {
            expiresAt = createdAt + expiresIn;
        }
        return System.currentTimeMillis() > expiresAt;
    }

    public boolean match(String token) {
        return this.token.equals(token);
    }

}
